package com.snail.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.model.dto.MistakesDto;
import com.snail.model.pojo.BizQuestion;
import com.snail.service.BizQuestionService;
import com.snail.service.BizUserQuestionMistakesService;
import com.snail.model.pojo.BizUserQuestionMistakes;
import com.snail.mapper.BizUserQuestionMistakesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Monica
* @description 针对表【biz_user_question_mistakes(用户错题表)】的数据库操作Service实现
* @createDate 2025-07-16 10:22:25
*/
@Service
public class BizUserQuestionMistakesServiceImpl extends ServiceImpl<BizUserQuestionMistakesMapper, BizUserQuestionMistakes>
    implements BizUserQuestionMistakesService {
    @Autowired
    private BizQuestionService bizQuestionService;

    @Override
    public List<MistakesDto> getMistakeQuestionsByUserId(int userId) {
        List<BizUserQuestionMistakes> mistakes = this.list(
                new QueryWrapper<BizUserQuestionMistakes>().eq("user_id", userId)
        );

        if (CollectionUtils.isEmpty(mistakes)) {
            return Collections.emptyList();
        }

        // Map<questionId, mistakeId>
        Map<Integer, Integer> questionMistakeMap = mistakes.stream()
                .collect(Collectors.toMap(
                        BizUserQuestionMistakes::getQuestionId,
                        BizUserQuestionMistakes::getId,
                        (oldVal, newVal) -> newVal // 若重复，保留最新
                ));

        List<Integer> questionIds = new ArrayList<>(questionMistakeMap.keySet());

        List<BizQuestion> questions = bizQuestionService.listByIds(questionIds);

        // 封装成 MistakesDto
        List<MistakesDto> result = questions.stream()
                .map(q -> {
                    MistakesDto dto = BeanUtil.copyProperties(q, MistakesDto.class);
                    dto.setMistakeId(questionMistakeMap.get(q.getId()));
                    return dto;
                })
                .collect(Collectors.toList());

        return result;
    }

    @Override
    public List<MistakesDto> searchMistakeQuestionsByContent(int userId, String keyword) {
        return baseMapper.searchMistakeQuestionsByContent(userId, keyword);
    }


}




